﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LiteExpress.Utilities
{

    public class SmtpConfig
    {
        public static string SmtpAddress { get; set; }        
        public static string SmtpAccount { get; set; }
        public static string SmtpPassword { get; set; }
        public static string SenderAddress { get; set; }
        public static string FromAddress { get; set; }
        public static string FromDisplayName { get; set; }
        public static bool EnableSSL { get; set; }
        public static int Port { get; set; }
    }

    public static class EmailHelper
    {
        /// <summary>
        /// 发送系统通知邮件辅助类，收件人为系统web.config文件配置内容
        /// </summary>
        /// <param name="to">收件人邮箱，多个用英文分号分隔</param>
        /// <param name="msg">邮件体内容，html</param>
        /// <param name="title">邮件标题</param>        
        /// <param name="fromEmail">如果需要设置回复人，则传入此参数，留空则默认使用配置中的回复人</param>
        /// <param name="attach">如果需要设置附件，则传入此参数</param>
        /// <returns>成功返回true,发送失败返回false</returns>
        public static bool NetSend(IEnumerable<string> to, string msg, string title
            , System.Net.Mail.MailAddress fromEmail = null
            , System.Net.Mail.Attachment attach = null, NameValueCollection header = null)
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();            
            foreach (string emailr in to)
            {
                message.To.Add(emailr);
            }

            if (attach != null)
            {
                message.Attachments.Add(attach);
            }

            message.Subject = title;

            if (fromEmail == null)
            {
                message.From = new System.Net.Mail.MailAddress(SmtpConfig.FromAddress, SmtpConfig.FromDisplayName);
            }
            else
            {
                message.From = fromEmail;
            }

            if (header != null)
            {
                message.Headers.Add(header);
            }

            message.Sender = new System.Net.Mail.MailAddress(SmtpConfig.SenderAddress);            
            message.Body = msg;
            message.IsBodyHtml = true;
            System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient(SmtpConfig.SmtpAddress);
            if (!string.IsNullOrWhiteSpace(SmtpConfig.SmtpAccount))
            {
                sc.UseDefaultCredentials = false;
                sc.Credentials = new System.Net.NetworkCredential(SmtpConfig.SmtpAccount, SmtpConfig.SmtpPassword);
            }
            sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            sc.EnableSsl = SmtpConfig.EnableSSL;
            sc.Port = SmtpConfig.Port;
            
            try
            {
                sc.Send(message);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static bool CDOSend(IEnumerable<string> to, string msg, string title
            , System.Net.Mail.MailAddress fromEmail = null
            , NameValueCollection header = null, string attachUrl = null)
        {
            CDO.Message objMail = new CDO.Message();
            try
            {
                objMail.Fields["urn:schemas:mailheader:uniqueid"].Value = Guid.NewGuid().ToString();
                if (header != null && header.Count > 0)
                {
                    foreach (var item in header.AllKeys)
                    {
                        objMail.Fields["urn:schemas:mailheader:" + item].Value = header[item];
                    }
                }
                objMail.Fields.Update();

                objMail.To = string.Join(",", to);

                System.Net.Mail.MailAddress fromaddr;
                if (fromEmail == null)
                {
                    fromaddr = new System.Net.Mail.MailAddress(SmtpConfig.FromAddress, SmtpConfig.FromDisplayName);
                }
                else
                {
                    fromaddr = fromEmail;
                }

                //附件暂未实现
                //var attach = objMail.Attachments.Add();
                //attach.DataSource.
                //attach.FileName


                //if (!string.IsNullOrWhiteSpace(attachUrl))
                //{ 
                //    objMail.AddAttachment(attachUrl);
                //}

                objMail.BodyPart.Charset = "utf-8";
                //from表示作者，sender通常为邮箱地址，代表发送人。replyto代表回复人，如果为空则从from中取
                objMail.From = string.Format("\"{0}\" <{1}>", fromaddr.DisplayName, fromaddr.Address);
                //objMail.ReplyTo 
                objMail.Sender = SmtpConfig.SenderAddress;                
                objMail.Subject = title;
                objMail.HTMLBody = msg;

                //ADODB.Fields;
                //objMail.Configuration.Fields.
                new Action<ADODB.Fields>((fields) => {
                    fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = SmtpConfig.Port; //设置端口
                    fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = SmtpConfig.SmtpAddress;
                    fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = CDO.CdoSendUsing.cdoSendUsingPort;
                    
                    if (!string.IsNullOrWhiteSpace(SmtpConfig.SmtpAccount))
                    {
                        fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = SmtpConfig.SmtpAccount;//information only
                        fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = SmtpConfig.SmtpAccount;
                        fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = SmtpConfig.SmtpPassword;
                        fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = CDO.CdoProtocolsAuthentication.cdoBasic;
                    }
                    else
                    {
                        fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = SmtpConfig.SenderAddress;//information only
                        fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = CDO.CdoProtocolsAuthentication.cdoAnonymous;
                    }

                    fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"].Value = SmtpConfig.EnableSSL;
                })(objMail.Configuration.Fields);

                #region hide
                //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = SmtpConfig.Port; //设置端口
                //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = SmtpConfig.SmtpAddress;
                //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = CDO.CdoSendUsing.cdoSendUsingPort;
                //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = SmtpConfig.SmtpAccount;//information only                
                //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = SmtpConfig.SmtpAccount;
                //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = SmtpConfig.SmtpPassword;
                //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value =CDO.CdoProtocolsAuthentication.cdoBasic;
                //objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"].Value = SmtpConfig.EnableSSL.ToString();
                #endregion
                objMail.Configuration.Fields.Update();
                objMail.Send();
                return true;
            }
            catch (Exception ex) {                
                //throw ex;
            }
            finally
            {
                //释放文件，这里没有附件所以不启用
                //GC.Collect();
                //GC.WaitForPendingFinalizers();            
                System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail);
                objMail = null;
            }
            return false;
        }

        //public static bool SendZhaopinEmailFile(IEnumerable<string> to, string msg, string title
        //    , System.Net.Mail.MailAddress fromEmail = null
        //    , NameValueCollection header = null)
        //{
 
        //}
    }
}
